// ==UserScript==
// @name                Net Disk Helper
// @name:zh-CN          网盘助手
// @name:ug             تور دىسكا ياردەمچىسى
// @namespace           https://github.com/ShererInc/NetDiskHelper
// @version             1.1.2
// @author              Sherer(شەرەر)
// @description         Easy to get material ids in net disk of Tianyi(189)
// @description:zh-CN   一键获取天翼云盘（189）素材ID
// @description:ug      ‫تىيەنيى (189) تور دىسكىسىدىكى ماتېرىياللارنىڭ نومۇرىغا ئاسانلا ئېرىشكىلى بولىدۇ
// @license             MIT
// @supportURL          https://github.com/ShererInc/NetDiskHelper
// @match               *://cloud.189.cn/web/main/*
// @require             https://unpkg.com/jquery@3.6.0/dist/jquery.min.js
// @require             https://unpkg.com/sweetalert2@10.16.6/dist/sweetalert2.all.min.js
// @run-at              document-idle
// @grant               GM_setClipboard
// @icon                
// ==/UserScript==

(function () {
    'use strict';

    // global variables
    const debug = false;
    const lang = navigator.language || navigator.userLanguage; // e.g. "en-US"

    // Language pack
    const languages = {
        'zh-CN': {
            dir: 'ltr',
            copy: '复制',
            copyed: '内容已复制',
            copy_url: '复制链接',
        },
        'ug': {
            dir: 'rtl',
            copy: 'كۆچۈرۈش',
            copyed: 'ئۇچۇر كۆچۈرۈلدى',
            copy_url: 'ئۇلانمىنى كۆچۈرۈش',
        },
        'default': {
            dir: 'ltr',
            copy: 'Copy',
            copyed: 'content has been copied',
            copy_url: 'Copy url',
        },
    };

    // Use i18n
    let tc = (key, locale = lang) => {
        if (languages[locale] && languages[locale][key]) {
            return languages[locale][key];
        } else if (languages['default'] && languages['default'][key]) {
            return languages['default'][key];
        } else {
            return key;
        }
    };

    // Toast
    let toast = Swal.mixin({
        toast: true,
        position: 'top',
        showConfirmButton: false,
        timer: 3500,
        timerProgressBar: false,
        customClass: {
            container: `${tc('dir')} sherer-font`,
        },
    });

    // Useful toast
    const message = {
        success: (text) => {
            toast.fire({ title: text, icon: 'success' });
        },
        error: (text) => {
            toast.fire({ title: text, icon: 'error' });
        },
        warning: (text) => {
            toast.fire({ title: text, icon: 'warning' });
        },
        info: (text) => {
            toast.fire({ title: text, icon: 'info' });
        },
        question: (text) => {
            toast.fire({ title: text, icon: 'question' });
        }
    };

    // Add style
    let style = document.createElement('style');
    style.innerHTML = `
        .ltr { direction: ltr !important; }
        .rtl { direction: rtl !important; }
        .sherer-btn { cursor: pointer; background-color: #f5f5f5; padding: 5px 8px; border-radius: 3px; white-space: nowrap; }
        .sherer-btn:hover { background-color: #e9e9e9; }
        .sherer-btn-tianyi { margin-right: 20px; padding: 4px 12px; border-radius: 4px; color: #fff; font-size: 12px; border: 1px solid #0073e3; background: #2b89ea; cursor: pointer; }
        .sherer-font { font-family: 'UKIJ Ekran', 'UKIJ Tor', 'UKIJ Basma', 'ALKATIP Tor', 'ALKATIP', 'Microsoft YaHei', '微软雅黑', 'PingFang SC', 'Helvetica Neue', Helvetica, Arial, sans-serif !important; }
        .sherer-flex-column { display: flex; flex-direction: column; }
        .sherer-justify-between { justify-content: space-between; }
        .sherer-position-none { position: static !important; }
        .sherer-center { text-align: center; }
        .sherer-m-5,.sherer-ml-5 { margin-left: 5px !important; }
        .sherer-m-5,.sherer-mr-5 { margin-right: 5px !important; }
        .sherer-m-5,.sherer-mt-5 { margin-top: 5px !important; }
        .sherer-m-5,.sherer-mb-5 { margin-bottom: 5px !important; }
        .sherer-my-5 { margin-top: 5px !important;margin-bottom: 5px !important; }
        .sherer-mx-5 {margin-left:5px !important;margin-right:5px !important;}
        .sherer-mx-auto {margin-left:auto;margin-right:auto;}
    `;
    document.head.appendChild(style);

    // Tianyi net disk
    const tianyi = () => {
        // $('.sherer-fileid').remove();
        let list = [];
        debug && console.log($('.file-list-ul .c-file-item[data-isfolder!="true"]').length);
        $('.file-list-ul .c-file-item[data-isfolder!="true"]').each(function () {
            let li = $(this);
            let fileid = li ? li.attr('data-fileid') : undefined;
            debug && console.log(fileid);
            if (!fileid) { return; }

            let _fieldid = `tianyi_${fileid}`;
            list.push(_fieldid)

            if (li.find(".sherer-fileid").length) { return; }
            li.find('.file-item').after(`<p class="sherer-fileid sherer-btn sherer-font sherer-center sherer-m-5" data-content="${_fieldid}">${tc('copy_url')}</p>`);
        });

        // Remove copy all button
        $('.sherer-copy-all').remove();

        // Add copy all data button
        if (list.length > 0) {
            // Add new copy all button
            let output = list.join('\n');
            $('.nav-opea').prepend(`<button type="button" class="sherer-btn-tianyi sherer-copy sherer-copy-all sherer-font" data-content="${output}">${tc('copy')}</button>`);
        }

        activeCopyEvent();
    };

    const copyContent = (content) => {
        if (!content) { return; }
        debug && console.log('copy text', content);
        GM_setClipboard(content, 'text');
        message.success(tc('copyed'));
    };

    // Add click event for copy content
    const activeCopyEvent = () => {
        $('.sherer-btn,.sherer-copy').off('click');
        $('.sherer-btn,.sherer-copy').on('click', function () {
            copyContent($(this).data('content'));
        });
    }

    // Analysis net disks
    if (/cloud.189.cn/.test(location.host)) {
        let observe = new MutationObserver(function (mutationsList, observer) {
            debug && console.log(mutationsList);
            let doWork = true;
            for (let i = 0; i < mutationsList.length; i++) {
                let mutation = mutationsList[i];
                if (mutation && mutation.addedNodes && mutation.addedNodes.length) {
                    let count = 0;
                    for (let j = 0; j < mutation.addedNodes.length; j++) {
                        let node = mutation.addedNodes[j];
                        if (node && node.classList && node.classList.contains('sherer-fileid')) {
                            count += 1;
                            break;
                        }
                    }
                    if (count > 0) { doWork = false; break; }
                }
            }
            doWork && tianyi();
        });

        let nodes = document.getElementsByClassName("p-view-box");
        debug && console.log(nodes);
        if (nodes && nodes.length) observe.observe(nodes.item(0), { attributes: false, childList: true, subtree: true });
        tianyi();
    }

    // active event
    activeCopyEvent();
})();